#pragma once
#include <iostream>
#include <string>
#include <string.h>
#include <errno.h>
#include <sys/shm.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

using namespace std;

const char *pathname = "/home/chineseperson04/CSDN/IPC/shared_memory";
int proj_id = 9;
const char *filename = "fifo";

const int size = 4096;

int GetKey()
{
    int key = ftok(pathname, proj_id);
    if (key == -1)
    {
        cout << "errno:" << errno << " strerror:" << strerror(errno) << endl;
        exit(2);
    }
    return key;
}

string ToHex(int key)
{
    char buffer[1024];
    snprintf(buffer, sizeof(buffer), "0x%x", key);
    return buffer;
}

int ShmHelper(int key, int flag)
{
    int shmid = shmget(key, size, flag);
    if (shmid == -1)
    {
        cout << "errno:" << errno << " strerror:" << strerror(errno) << endl;
        exit(2);
    }
    return shmid;
}

int CreateShm(int key)
{
    return ShmHelper(key, IPC_CREAT | IPC_EXCL | 0666);
}

int GetShm(int key)
{
    return ShmHelper(key, IPC_CREAT);
}

// 创建命名管道
bool MakeFifo()
{
    int n = mkfifo(filename, 0666);
    if (n < 0)
    {
        cerr << "errno" << errno << "strerror" << strerror(errno) << endl;
        return false;
    }
    cout << "create fifo success..." << endl;
    return true;
}